package com.weight

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.EditText
import com.common.R

/**
 * Created by chentao on 2017/8/8.
 */
class ClearEditText(context: Context, attributeSet: AttributeSet) : EditText(context, attributeSet) {
    private var showDrawable: Boolean = false

    init {
        setDrawVisibility(false)
        addTextChangedListener(object: TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                setDrawVisibility(text.length > 0)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        } )
    }

    fun setDrawVisibility(visibility: Boolean) {
        showDrawable = visibility
        if(visibility) {
            val drawable = context.resources.getDrawable(R.mipmap.search_cancel)
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            setCompoundDrawables(null, null, drawable, null)
        } else {
            setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], null, compoundDrawables[3])
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if(showDrawable && event?.action == MotionEvent.ACTION_UP) {
            //totalPaddingRight 右侧padding和图标之和
            if(event.x > width - totalPaddingRight && event.x < width - paddingRight)
                setText("")
        }
        return super.onTouchEvent(event)
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        setDrawVisibility(focused && text.length > 0)
    }

    override fun onDraw(canvas: Canvas?) {
        val paint = Paint()
        paint.color = Color.parseColor("#939393")
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 3F
        canvas?.drawLine(0f, height.toFloat(), width.toFloat(), height.toFloat(), paint)
        super.onDraw(canvas)
    }
}